package rsj.service.account;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import rsj.api.account.entity.AccountQueryParam;
import rsj.api.account.entity.Finance;
import rsj.api.contract.entity.Contract;
import common.entity.PageInfo;
import rsj.service.contract.IContractService;
import rsj.sql.finance.FinanceDao;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 财务
 *
 * @author yuanqinglong
 * @since 2021/7/15 10:39
 */
@Service
public class FinanceServiceImpl implements IFinanceService {


    @Autowired
    private FinanceDao financeDao;

    @Autowired
    private IContractService contractServiceImpl;


    /**
     * 财务列表
     *
     * @param accountQueryParam 账户查询参数
     * @return {@link List<Finance>}
     */
    @Override
    public List<Finance> financeList(AccountQueryParam accountQueryParam) {
        PageInfo pageInfo = accountQueryParam.getPageInfo();
        TableNode tableNode = financeDao.financeList(accountQueryParam.getAutKeyid(), accountQueryParam.getCustSname(), accountQueryParam.getCustId(), pageInfo.getPageSize(), pageInfo.getPageOffSet());
        List<Finance> financeList = JSON.parseArray(tableNode.toJson(), Finance.class);
        if (CollectionUtils.isEmpty(financeList)) {
            return financeList;
        }
        List<String> orgIds = financeList.stream().map(Finance::getOrgId).collect(Collectors.toList());
        List<Contract> contracts = contractServiceImpl.combinationContract(orgIds);
        Map<String, List<Contract>> organizeContractGroups = contracts.stream().collect(Collectors.groupingBy(Contract::getOrgpOrgId));
        financeList.forEach(finance -> finance.processingServiceValidityPeriod(organizeContractGroups.getOrDefault(finance.getOrgId(), Collections.emptyList())));
        return financeList;
    }


    /**
     * 金融统计
     *
     * @param accountQueryParam 账户查询参数
     * @return int
     */
    @Override
    public int financeCount(AccountQueryParam accountQueryParam) {
        Node financeCount = financeDao.financeCount(accountQueryParam.getAutKeyid(), accountQueryParam.getCustSname(), accountQueryParam.getCustId());
        return financeCount.valueInt();
    }


}
